package com.cjzuji.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cjzuji.rental.dao.*;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.OrderBill;
import com.cjzuji.rental.pojo.Orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ErSRRZSaveServiceImpl {
    @Autowired
    RenRZuContractDao RenRZuContractDao;
    @Autowired
    ErSRRZOrderDao erSRRZOrderDao;
    @Autowired
    RenRZuBillDao RenRZuBillDao;
    @Autowired
    RenRZuUserDao RenRZuUserDao;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderBillMapper orderBillMapper;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    private static final Logger logger = LoggerFactory.getLogger(ErSRRZSaveServiceImpl.class);
    // 事务要加Propagation.REQUIRES_NEW：是独立事务，每次都会创建一个新的事务
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void extractionSave(Map<String, Object> item,Map<String, Object> detail, Map<String, Object> amountlist,
                               List<Map<String, Object>> contract, List<Map<String, Object>> bill, String authorization,
                               String orderId, String uesrName, String userPhone, String userIdcard, String userAddress) {
        try {
            //保存到数据库
            // 判断 当前的订单号是否在数据库中存在 如果存在  跳出当前循环
            //System.out.println("正在判断订单是否已存在");
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id",orderId);
            List<Orders> existingOrder = orderMapper.selectList(queryWrapper);
            logger.info("existingOrder {}",existingOrder);
            if (existingOrder.size() > 0 ) {
                // 订单已存在，跳过当前循环
                logger.info("订单已存在，跳过当前循环");
                //更新订单状态和快递号
                UpdateWrapper<Orders> orderupdateWrapper = new UpdateWrapper<>();
                orderupdateWrapper.eq("order_id",orderId)
                        .set("status",getOrderStatus(detail.get("order_status").toString()));
                logger.info("更新订单状态成功！"+getOrderStatus(detail.get("order_status").toString()));
                orderMapper.update(orderupdateWrapper);

            } else {
                logger.info("正在保存Order~~~~~~~~~~");
                Long orderID = erSRRZOrderDao.save(item,detail, amountlist, uesrName, userPhone, userIdcard);
                logger.info("正在保存User~~~~~~~~~~");
                RenRZuUserDao.save(detail, orderID, uesrName, userPhone, userAddress, userIdcard);
                //contract不为空，null
                if (contract != null && contract.size() > 0) {
                    logger.info("正在保存Contract~~~~~~~~~~");
                    RenRZuContractDao.save(contract, orderID);
                    // System.out.println("保存成功~~~");
                }
                //bill不为 空，null
                if (bill != null && bill.size() > 0) {
                    logger.info("正在保存Bill~~~~~~~~~~");
                    RenRZuBillDao.save(bill, orderID);
                    //System.out.println("保存成功~~~");
                }
                logger.info("事务提交成功！");
            }
        } catch (Exception e) {
            // 回滚事务
//            transactionManager.rollback(status);
            logger.error("保存数据时发生异常~~~~~~~~~~~~", e);
            throw new RuntimeException(e); // 确保抛出异常以回滚事务
        }
    }

    //租用中更新账单和合同
    public void extractionSave(Map<String,Object> detail,Map<String, Object> amountlist,Map<String, Object> riskData,List<Map<String, Object>> contract,List<Map<String, Object>> bill,String orderId) {
        try {
            // 更新风控信息
            logger.info("orderId~~~~~~~~~~"+orderId);
            UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
            if (riskData.containsKey("risk_levels")){
                Map<String, Object> riskLevels = (Map<String, Object>) riskData.get("risk_levels");
                updateWrapper.eq("order_id",orderId)
                        .set("opinion", riskLevels.get("value").toString());
                orderMapper.update(updateWrapper);
                logger.info("更新风控信息成功！");
            }else{
                Map<String, Object> riskInfo = (Map<String, Object>) riskData.get("risk_qualitative");
                updateWrapper.eq("order_id",orderId)
                        .set("opinion", riskInfo.get("value").toString());
                orderMapper.update(updateWrapper);
                logger.info("更新风控信息成功！~~~~");
            }
            // 当前的订单号是否在数据库中存在 如果存在  跳出当前循环
            QueryWrapper<OrderBill> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orders_id",orderId);
            List<OrderBill> existingBill = orderBillMapper.selectList(queryWrapper);
            logger.info("查询到的已存在账单数量: {}",existingBill.size());
            // 订单已存在
            if (!existingBill.isEmpty() ) {
                Long orderID = existingBill.get(0).getOrderId();
                // 订单已存在，对比两方的“还款状态”数据，如果相同不变，不同对数据库账单表进行更新
                logger.info("订单已存在~~,对比更新数据",orderId);
                compareUpdate(bill,existingBill,orderID);
            }
            else {
                QueryWrapper<Orders> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("order_id",orderId);
                Orders order = orderMapper.selectOne(orderWrapper);
                if(order != null){
                    //更新orders表中的订单状态，快递单号
                    UpdateWrapper<Orders> orderupdateWrapper = new UpdateWrapper<>();
                    orderupdateWrapper.eq("order_id",orderId)
                            .set("status",3)
                            .set("delivery_no",detail.get("logistic_number").toString());
                    logger.info("更新订单状态和快递号成功！");
                    orderMapper.update(orderupdateWrapper);
                    Long orderID = order.getId();
                    logger.info("添加合同表~~",orderId);
                    RenRZuContractDao.save(contract, orderID);
                    logger.info("添加账单表~~",orderId);
                    RenRZuBillDao.save(bill, orderID);
                }else {
                    logger.info("Orders表中未找到订单~~~",orderId);
                }
                // 手动提交事务
                logger.info("事务提交成功！");
            }
        } catch (Exception e) {
            // 回滚事务
            logger.error("保存数据时发生异常~~~~~~~~~~~~", e);
            throw new RuntimeException(e); // 确保抛出异常以回滚事务
        }
    }

    //对比更新代码
    public void compareUpdate(List<Map<String, Object>> billDtoList, List<OrderBill> existingBill, Long orderID) {
        //System.out.println("billDtoList~~:"+billDtoList);
        //创建一个Map，用于存储数据库中的账单
        Map<Integer, OrderBill> existingBillMap = new HashMap<>();
        for (OrderBill bill : existingBill) {
            existingBillMap.put(bill.getTerm(), bill);
        }
        //logger.info("existingBillMap {}",existingBillMap);
        for (Map<String, Object> billDto : billDtoList) {
            String zuqi=billDto.get("期数").toString();
            int term = Integer.parseInt(zuqi.split("/")[0]) ;
            String newStatus = billDto.get("支付状态") != null ? billDto.get("支付状态").toString() : "";
            OrderBill oldBill = existingBillMap.get(term);
            if (oldBill != null) {
                //对比订单状态
                String oldStatus = oldBill.getRepayStatusStr() != null ? oldBill.getRepayStatusStr() : "";
                //System.out.println("oldStatus~~ " + oldStatus);
                if(!newStatus.equals(oldStatus)){
                    //状态不同
                    logger.info("状态不同，第{}期~~", term);
                    UpdateWrapper<OrderBill> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", oldBill.getId())
                            .set("real_pay_time", billDto.get("实际支付日 ")) //支付时间
                            .set("real_pay_capital", billDto.get("实付金额 表示用户实际支付租金；当账单为【支付完成】状态时，实付金额+支付优惠金额=账单金额； 平台以【实付金额】进行租金结算；"))  //还款金额
                            .set("repay_status_str", newStatus) // 还款状态
                            .set("real_repay_time", billDto.get("实际支付日"))//还款时间
                            .set("update_time", new Date());
                    logger.info("更新账单信息成功！");
                    orderBillMapper.update(updateWrapper);
                }else {
                    //logger.info("状态相同，第{}期~~", term);
                }
            }
        }
    }
    //订单状态枚举
    public int getOrderStatus(String status) {
        switch (status) {
            case "4":   //订单状态   3租用中
                return 3 ;
            case "5":
                return 3 ;
            case "33":
                return 3 ;
            case "20":    //订单状态   5已完成
                return 5 ;
            default:
                return 7 ;
        }
    }
}
